package com.yjz.zpay.ui;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.yjz.zpay.R;
import com.yjz.zpay.bean.NotifyResult;
import com.yjz.zpay.bean.OrderBean;
import com.yjz.zpay.boradcast.AlarmReceiver;
import com.yjz.zpay.db.DBManager;
import com.yjz.zpay.service.DaemonService;
import com.yjz.zpay.utils.JSONParser;
import com.yjz.zpay.utils.L;
import com.yjz.zpay.utils.MD5Utils;
import com.yjz.zpay.utils.PayHelperUtils;
import com.yjz.zpay.utils.SpUtils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends AppCompatActivity {

    public static TextView console;
    private static ScrollView scrollView;
    private BillReceived billReceived;
    private AlarmReceiver alarmReceiver;
    public static String BILLRECEIVED_ACTION = "com.tools.payhelper.billreceived";
    public static String QRCODERECEIVED_ACTION = "com.tools.payhelper.qrcodereceived";
    public static String MSGRECEIVED_ACTION = "com.tools.payhelper.msgreceived";
    public static String TRADENORECEIVED_ACTION = "com.tools.payhelper.tradenoreceived";
    public static String LOGINIDRECEIVED_ACTION = "com.tools.payhelper.loginidreceived";
    public static String NOTIFY_ACTION = "com.tools.payhelper.notify";

    private String currentAlipay = "";
    public static EditText et;
    private TextView tvUser, tvApp;
    private Button btnHeart;

    private Context mContext;
    private DBManager dbManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //不息屏
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        mContext = this;
        setContentView(R.layout.activity_main);
        console = findViewById(R.id.console);
        scrollView = findViewById(R.id.scrollview);
        et = findViewById(R.id.et);
        tvUser = findViewById(R.id.tv_user);
        tvApp = findViewById(R.id.tv_app);
        btnHeart = findViewById(R.id.btn_heart);



        btnHeart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String host = SpUtils.getString(getApplicationContext(), "host");
                String key = SpUtils.getString(getApplicationContext(), "key");
                String agencyId = SpUtils.getString(getApplicationContext(), "agencyId");
                String appId = SpUtils.getString(getApplicationContext(), "appId");

                if (TextUtils.isEmpty(host) || TextUtils.isEmpty(key) || TextUtils.isEmpty(agencyId) || TextUtils.isEmpty(appId)) {
                    Toast.makeText(mContext, "请先配置数据", Toast.LENGTH_SHORT).show();
                    return;
                }


                if (heartTimer == null) {
                    startHeart();
                    btnHeart.setText("停止心跳");
                } else {
                    heartTimer.cancel();
                    heartTimer = null;
                    btnHeart.setText("开始心跳");
                }
            }
        });

        dbManager = new DBManager(this);


        this.findViewById(R.id.setting).setOnClickListener(
                new View.OnClickListener() {

                    @Override
                    public void onClick(View arg0) {
                        Intent intent = new Intent(MainActivity.this, SettingActivity.class);
                        startActivity(intent);
                    }
                });


        //注册广播
        billReceived = new BillReceived();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BILLRECEIVED_ACTION);
        intentFilter.addAction(MSGRECEIVED_ACTION);
        intentFilter.addAction(QRCODERECEIVED_ACTION);
        intentFilter.addAction(TRADENORECEIVED_ACTION);
        intentFilter.addAction(LOGINIDRECEIVED_ACTION);
        intentFilter.addAction(PayHelperUtils.Action_SaveSpParams);
        intentFilter.addAction(PayHelperUtils.GET_PERSON_MOENY_NOTICE);
        registerReceiver(billReceived, intentFilter);


        alarmReceiver = new AlarmReceiver();
        IntentFilter alarmIntentFilter = new IntentFilter();
        alarmIntentFilter.addAction(NOTIFY_ACTION);
        registerReceiver(alarmReceiver, alarmIntentFilter);

        //start service
        startService(new Intent(mContext, DaemonService.class));
    }


    public static Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            final String txt = msg.getData().getString("log");
            if (console != null) {
                if (console.getText() != null) {
                    if (console.getText().toString().length() > 5000) {
                        console.setText("日志定时清理完成..." + "\n\n" + txt);
                    } else {
                        console.setText(console.getText().toString() + "\n\n" + txt);
                    }
                } else {
                    console.setText(txt);
                }
                scrollView.post(new Runnable() {
                    public void run() {
                        scrollView.fullScroll(View.FOCUS_DOWN);
                    }
                });
            }
            super.handleMessage(msg);
        }

    };


    @Override
    protected void onDestroy() {
        unregisterReceiver(alarmReceiver);
        unregisterReceiver(billReceived);
        if (heartTimer != null) {
            heartTimer.cancel();
            heartTimer = null;
        }
        super.onDestroy();
    }


    public static void sendmsg(String txt) {
        Message msg = new Message();
        msg.what = 1;
        Bundle data = new Bundle();
        long l = System.currentTimeMillis();
        Date date = new Date(l);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String d = dateFormat.format(date);
        data.putString("log", d + ":" + "  结果:" + txt);
        msg.setData(data);
        try {
            handler.sendMessage(msg);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onBackPressed() {
        moveTaskToBack(true);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // 过滤按键动作
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
            moveTaskToBack(true);
        }
        return super.onKeyDown(keyCode, event);
    }

    //自定义接受订单通知广播
    class BillReceived extends BroadcastReceiver {
        @Override
        public void onReceive(final Context context, Intent intent) {
            try {
                if (intent.getAction().contentEquals(BILLRECEIVED_ACTION)) {
                    /**收到支付宝付款订单**/
                    String orderNo = intent.getStringExtra("bill_no");
                    String money = intent.getStringExtra("bill_money");
                    String type = intent.getStringExtra("bill_type");
                    String payUserId = intent.getStringExtra("bill_pay_user_id");
                    String remark = intent.getStringExtra("bill_remark");
                    String payType = intent.getStringExtra("bill_pay_type");
                    long time = new Date().getTime();

                    String typestr = "";
                    if (type.equals("alipay")) {
                        typestr = "支付宝";
                    }

                    String payTypeStr = "";
                    if (payType.equals("5")) {
                        payTypeStr = "充值";
                    } else if (payType.equals("1")) {
                        payTypeStr = "扫码";
                    }

                    if (!dbManager.isExistAliBOrder(orderNo)) {
                        sendmsg("收到" + typestr + "订单,\n方式:" + payTypeStr + "\n订单号：" + orderNo + "\n金额：" + money + "\n备注:" + remark);
                        dbManager.addOrder(new OrderBean(money, orderNo, "", payUserId));
                        //发送异步通知
                        notifyapi(payType, orderNo, money, payUserId, remark, time, 0);
                    }

                } else if (intent.getAction().contentEquals(MSGRECEIVED_ACTION)) {
                    String msg = intent.getStringExtra("msg");
                    sendmsg(msg);
                } else if (intent.getAction().contentEquals(LOGINIDRECEIVED_ACTION)) {
                    String loginid = intent.getStringExtra("loginid");
                    String loginAccount = intent.getStringExtra("loginAccount");
                    String type = intent.getStringExtra("type");
                    if (!TextUtils.isEmpty(loginAccount)) {
                        if (type.equals("alipay") && !loginAccount.equals(currentAlipay)) {
                            sendmsg("当前登录支付宝账号userId：" + loginid + "--" + loginAccount);
                            currentAlipay = loginAccount;
                            SpUtils.putString(getApplicationContext(), type, loginid);
                            SpUtils.putString(getApplicationContext(), "alipayAccount", loginAccount);

//                            PayHelperUtils.startAlipayMonitor(mContext);
                        }
                    }
                }
            } catch (Exception e) {
                PayHelperUtils.sendmsg(context, "BillReceived异常" + e.getMessage());
            }
        }
    }


    /**
     * 开启心跳
     */
    Timer heartTimer;

    private void startHeart() {

        if (heartTimer != null) {
            return;
        }

        try {
            heartTimer = new Timer();
            TimerTask timerTask = new TimerTask() {
                @Override
                public void run() {
                    Log.d("#####", "心跳...");
                    heartCheck();
                }
            };
            int triggerTime = 30;
            heartTimer.schedule(timerTask, 0, triggerTime * 1000);
        } catch (Exception e) {

        }
    }


    public void heartCheck() {
        try {
            String host = SpUtils.getString(getApplicationContext(), "host");
            String key = SpUtils.getString(getApplicationContext(), "key");
            String agencyId = SpUtils.getString(getApplicationContext(), "agencyId");
            String appId = SpUtils.getString(getApplicationContext(), "appId");

            String notifyurl = "http://" + host + "/appHeart";

            long time = new Date().getTime();

            String sign = MD5Utils.encode(agencyId + appId + time + key);
            OkGo.<String>post(notifyurl)
                    .params("applyId", appId)
                    .params("userId", agencyId)
                    .params("t", time)
                    .params("sign", sign)   //验签

                    .execute(new StringCallback() {
                        @Override
                        public void onSuccess(Response<String> response) {
                            L.d("##########--->心跳返回" + response.body().toString());

                            NotifyResult result = (NotifyResult) JSONParser.toObject(response.body().toString(), NotifyResult.class);
                            if (result != null && result.getCode() == 200) {
                                sendmsg("心跳成功__" + result.getMessage());
                            } else {
                                sendmsg("心跳失败__" + result.getMessage());
                            }
                        }

                        @Override
                        public void onError(Response<String> response) {
                            L.d("##########--->异步通知错误");

                            sendmsg("心跳接口出错\n" + response.getException().getMessage());
                            super.onError(response);
                        }
                    });
        } catch (Exception e) {
            sendmsg("notifyapi异常" + e.getMessage());
        }
    }


    /**
     * 调用后端地址 通知订单支付成功(事先设置notifyurl)
     *
     * @param payType
     * @param orderNo
     * @param money
     */
    public void notifyapi(final String payType, final String orderNo, final String money, final String payUserId, final String remark, final long time, final int count) {
        try {
            String host = SpUtils.getString(getApplicationContext(), "host");
            String key = SpUtils.getString(getApplicationContext(), "key");
            String agencyId = SpUtils.getString(getApplicationContext(), "agencyId");
            String appId = SpUtils.getString(getApplicationContext(), "appId");

            String notifyurl = "http://" + host + "/appPush";

            L.d(host + "--" + key + "--" + agencyId + "--" + appId + "--+" + notifyurl);

            String sign = MD5Utils.encode(agencyId + appId + payType + money + orderNo + time + key);
            OkGo.<String>post(notifyurl)
                    .params("applyId", appId)
                    .params("userId", agencyId)
                    .params("type", payType)
                    .params("orderId", orderNo)
                    .params("price", money)
                    .params("t", time)
                    .params("sign", sign)   //验签

                    .execute(new StringCallback() {
                        @Override
                        public void onSuccess(Response<String> response) {
                            L.d("##########--->异步通知" + response.body().toString());

                            NotifyResult result = (NotifyResult) JSONParser.toObject(response.body().toString(), NotifyResult.class);
                            if (result != null && result.getCode() == 200) {
                                sendmsg("支付宝回调成功" + "\n流水号:" + orderNo);
                                dbManager.updateOrder(orderNo, "success");
                            } else {
                                sendmsg("支付宝回调失败" + "\n流水号:" + orderNo);
                            }
                        }

                        @Override
                        public void onError(Response<String> response) {
                            super.onError(response);
                            L.d("##########--->异步通知错误");
                            if (count == 0) {
                                notifyapi(payType, orderNo, money, payUserId, remark, time, 1);
                            } else {
                                sendmsg("支付宝回调失败" + "\n流水号:" + orderNo);
                            }
                        }
                    });
        } catch (Exception e) {
            sendmsg("notifyapi异常" + e.getMessage());
        }
    }

    private void moveToFont() {
        Intent start = new Intent(getApplicationContext(), MainActivity.class);
        start.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
        startActivity(start);
    }


    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
    }


    @Override
    protected void onResume() {
        String user = SpUtils.getString(getApplicationContext(), "agencyId");
        String appId = SpUtils.getString(getApplicationContext(), "appId");
        if (!TextUtils.isEmpty(user) && !TextUtils.isEmpty(appId)) {
            tvUser.setText("商户ID:" + user);
            tvApp.setText("应用ID:" + appId);
        }

        super.onResume();
    }
}
